package com.example.service.impl;

import com.example.dto.LoginRequest;
import com.example.dto.LoginResponse;
import com.example.entity.SysUser;
import com.example.mapper.SysUserMapper;
import com.example.service.SysUserService;
import com.example.util.JwtUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户Service实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    
    private final SysUserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    public SysUserServiceImpl(SysUserMapper userMapper, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }
    
    @Override
    public LoginResponse login(LoginRequest request) {
        // 根据用户名查询用户
        SysUser user = findByUsername(request.getUsername());
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        
        // 验证密码
        if (!validatePassword(request.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        
        // 生成Token
        String token = jwtUtil.generateToken(user.getUsername());
        
        // 返回登录响应
        return new LoginResponse(
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                token
        );
    }
    
    @Override
    public SysUser findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    @Override
    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
    }
} 